package com.hong.pro.utils;

import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatCompletionResult;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.completion.chat.ChatMessageRole;
import com.theokanning.openai.service.OpenAiService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description:
 * @Author Hong Qiang
 * @Date 2023/11/27 15:11
 * @Version 1.0
 */
public class OpenApiUtil {
    public static void main(String[] args) {

        System.setProperty("java.net.useSystemProxies", "true");
        System.setProperty("http.proxyHost", "127.0.0.1");
        System.setProperty("http.proxyPort", "7890");
        System.setProperty("https.proxyHost", "127.0.0.1");
        System.setProperty("https.proxyPort", "7890");

        OpenAiService service = new OpenAiService("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");
        List<ChatMessage> chatMessages=new ArrayList<>();
        ChatMessage chatMessage =new ChatMessage();
        chatMessage.setRole("user");
        chatMessage.setContent("你好");
        chatMessages.add(chatMessage);

        System.out.println("\nCreating completion...");
        ChatCompletionRequest completionRequest = ChatCompletionRequest.builder()
                .model("gpt-3.5-turbo-0301").messages(chatMessages).build();
        service.createChatCompletion(completionRequest).getChoices().forEach(System.out::println);
//        CompletionRequest completionRequest = CompletionRequest.builder()
//                .prompt("Somebody once told me the world is gonna roll me")
//                .model("ada")
//                .echo(true)
//                .build();
//        service.createCompletion(completionRequest).getChoices().forEach(System.out::println);
    }

    public static ChatCompletionResult createChatCompletion(List<ChatMessage> messages) {
        // 需要申请ApiKey
        OpenAiService service = new OpenAiService("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");

        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                // 模型名称
                .model("gpt-3.5-turbo")
                // 下面两项数值控制模型输出的随机性，对回答的稳定性要求高时，可设置随机性为最低
                .temperature(0.0D)
                .topP(1.0)
                .messages(messages)
                .build();
        return service.createChatCompletion(chatCompletionRequest);
    }
}
